#!/bin/bash

# SmartInput 图标生成脚本
# 将SVG占位符转换为真正的PNG图标

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 检查依赖
check_dependencies() {
    echo -e "${BLUE}[INFO]${NC} 检查依赖..."
    
    # 检查ImageMagick
    if ! command -v convert &> /dev/null; then
        echo -e "${RED}[ERROR]${NC} 需要安装ImageMagick"
        echo "Ubuntu/Debian: sudo apt-get install imagemagick"
        echo "CentOS/RHEL: sudo yum install ImageMagick"
        echo "macOS: brew install imagemagick"
        exit 1
    fi
    
    echo -e "${GREEN}[SUCCESS]${NC} 依赖检查完成"
}

# 生成图标
generate_icons() {
    echo -e "${BLUE}[INFO]${NC} 生成PNG图标..."
    
    # 创建临时SVG文件
    create_temp_svg
    
    # 生成不同尺寸的图标
    convert_icon 16
    convert_icon 32
    convert_icon 48
    convert_icon 128
    
    echo -e "${GREEN}[SUCCESS]${NC} 图标生成完成"
}

# 创建临时SVG文件
create_temp_svg() {
    cat > temp_icon.svg << 'EOF'
<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
      <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
    </linearGradient>
  </defs>
  <rect width="128" height="128" rx="20" fill="url(#grad1)"/>
  <circle cx="64" cy="64" r="40" fill="white" opacity="0.9"/>
  <circle cx="64" cy="64" r="30" fill="#667eea"/>
  <path d="M 64 44 L 64 84 M 54 64 L 74 64" stroke="white" stroke-width="4" stroke-linecap="round"/>
</svg>
EOF
}

# 转换图标
convert_icon() {
    local size=$1
    echo -e "${BLUE}[INFO]${NC} 生成 ${size}x${size} 图标..."
    
    convert temp_icon.svg -resize ${size}x${size} icons/icon${size}.png
}

# 清理临时文件
cleanup() {
    echo -e "${BLUE}[INFO]${NC} 清理临时文件..."
    rm -f temp_icon.svg
    echo -e "${GREEN}[SUCCESS]${NC} 清理完成"
}

# 验证图标
verify_icons() {
    echo -e "${BLUE}[INFO]${NC} 验证图标文件..."
    
    local sizes=(16 32 48 128)
    for size in "${sizes[@]}"; do
        if [ -f "icons/icon${size}.png" ]; then
            local file_type=$(file "icons/icon${size}.png" | grep -o "PNG image")
            if [ "$file_type" = "PNG image" ]; then
                echo -e "${GREEN}[SUCCESS]${NC} icon${size}.png 验证通过"
            else
                echo -e "${RED}[ERROR]${NC} icon${size}.png 不是有效的PNG文件"
            fi
        else
            echo -e "${RED}[ERROR]${NC} icon${size}.png 文件不存在"
        fi
    done
}

# 主函数
main() {
    echo "=== SmartInput 图标生成工具 ==="
    echo ""
    
    check_dependencies
    generate_icons
    verify_icons
    cleanup
    
    echo ""
    echo -e "${GREEN}[SUCCESS]${NC} 所有图标生成完成！"
    echo "现在可以正常打包扩展了。"
}

# 运行主函数
main "$@"
